import random
from io import BytesIO

from PIL import Image

from captcha.image import ImageCaptcha


def gen_captcha(content='0123456789'):
    image_captcha = ImageCaptcha()
    # 获取随机字符
    captcha_text = ''.join(random.choices(content, k=4))
    # 生成图片验证码
    data = image_captcha.generate(captcha_text)
    # 生成图像
    captcha_image = Image.open(data)

    return captcha_text, captcha_image


# 生成验证码
def get_captcha_code_and_content():
    code, image = gen_captcha()
    out = BytesIO()
    image.save(out, "png")
    out.seek(0)
    content = out.read()  # 读取图片的二进制数据做成响应体
    return code, content


if __name__ == '__main__':
    # print(gen_captcha())
    code, content = get_captcha_code_and_content()
    print(type(code), type(content))